<?php
/**
 * Este bootstrap permite correr la aplicacion tambien desde la consola.
 */

class Webf_Controller_Router_Cli extends Zend_Controller_Router_Abstract implements Zend_Controller_Router_Interface {
    public function assemble($userParams, $name = null, $reset = false, $encode = true) { }
    public function route(Zend_Controller_Request_Abstract $dispatcher) {}
}

class Ext_Application_Bootstrap_Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    /**
     * Run the application
     *
     * Checks to see that we have a default controller directory. If not, an
     * exception is thrown.
     *
     * If so, it registers the bootstrap with the 'bootstrap' parameter of
     * the front controller, and dispatches the front controller.
     *
     * @return void
     * @throws Zend_Application_Bootstrap_Exception
     */
    public function run()
    {
        $front   = $this->getResource('FrontController');
        $default = $front->getDefaultModule();
        if (null === $front->getControllerDirectory($default)) {
            throw new Zend_Application_Bootstrap_Exception(
                'No default controller directory registered with front controller'
            );
        }
        $front->setParam('bootstrap', $this);


        // Running from CLI
        // @todo: reveer esto.
        global $argv;
        if ( ! empty( $argv ) ) {
            try {
                $opts = new Zend_Console_Getopt(
                    array(
                        'help|h' => 'Displays usage information.',
                        'action|a=s' => 'Action to perform in format of module.controller.action'
                    )
                );
                $opts->parse();
            } catch (Zend_Console_Getopt_Exception $e) {
                exit( $e->getMessage() ."\n\n". $e->getUsageMessage() );
            }
            if( isset( $opts->a ) ) {
                $reqRoute = array_reverse( explode( '.', $opts->a ) );
                @list( $action, $controller, $module ) = $reqRoute;
                $front->setRequest( new Zend_Controller_Request_Simple( $action, $controller, $module ) );
                $front->setRouter( new Webf_Controller_Router_Cli() );
                $front->setResponse( new Zend_Controller_Response_Cli() );
            } else {
                echo $opts->getUsageMessage();
                exit;
            }
        }
        // CLI END.
        $front->dispatch();
    }
}
